package bid

import (
	"errors"
	"wx-api/adx-bid/cache"
	"wx-api/adx-bid/services/common"
	"wx-api/adx-bid/utils"
)

func HBid(sty, id, name, cty string, isdebug bool, body []byte) (interface{}, string, error) {
	adx_info, ok := cache.CacheAdxListMapGet(sty + id)
	if !ok || adx_info == nil {
		common.PriMsg(isdebug, "HBid====adx_info is empty:"+sty+id+"="+name)
		return nil, "", errors.New("adx info is empty")
	}
	//媒体数据解析
	req, mreq, hty, err := MediaBodyDecode(body, adx_info.AdxTypeId, cty)
	if err != nil {
		common.PriMsg(isdebug, err.Error())
		return nil, "", errors.New("adx decode is error:" + err.Error())
	}
	req.BidId = utils.GetUUid()
	//参数统一处理
	errp := MediaDoParam(req)
	if errp != nil {
		common.PriMsg(isdebug, errp.Error())
		return nil, "", errors.New("adx param is error:" + errp.Error())
	}
	m_info, s_info, errt := SelSlot(sty, adx_info, req)
	if errt != nil {
		common.PriMsg(isdebug, errt.Error())
		return nil, "", errors.New("adx param is error:" + errt.Error())
	}
	//媒体请求记录
	go MediaReqMsg(sty, req, adx_info, m_info, s_info)
	//广告竞价
	bid, plid, did, pid, errb := Plan(isdebug, sty, req, adx_info, m_info, s_info)
	if errb != nil || bid == nil {
		common.PriMsg(isdebug, errb.Error())
		return nil, "", errors.New("adx bids is error:" + errb.Error())
	}
	//媒体返回数据处理
	res, errs := MediaBodyEncode(mreq, bid, adx_info.AdxTypeId, cty)
	if errs != nil {
		common.PriMsg(isdebug, errs.Error())
		return nil, "", errors.New("adx encode is error:" + errs.Error())
	}
	//广告返回媒体记录
	go MediaResMsg(sty, req, adx_info, m_info, s_info, plid, did, pid)
	return res, hty, nil
}
